<html>
  <head>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/menu/assets/skins/sam/menu.css">
    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/container/assets/skins/sam/container.css" />
    <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.2/build/calendar/assets/skins/sam/calendar.css">

    <link rel="stylesheet" type="text/css" href="/static/stylesheets/datatable.css">
    <link rel="stylesheet" type="text/css" href="/static/stylesheets/main.css" />

    {{title}}
  </head>
  <body class="yui-skin-sam">
  {{header}}
  
  <span id="description" class="project">{{project.description}}</span>
  {% if project.is_complete %}
  <span id="completed" class="completed">[Completed]</span>
  {% endif %}
  <span id="edit_description" class="hint">(<a href="javascript:editDescription()">edit description</a>)</span>

  <br />
  <br />
  <b>Project Tasks:</b><br />
  <div id="project_section" class="grid">
      <table id="tasks">
          <thead>
              <tr>
                  <th>Task</th>
                  <th>Due Date</th>
                  <th>Complete?</th>
              </tr>
          </thead>
          <tbody>
          {% for task in project.subtasks %}
            <tr>
              <td>{{task.key_action_string}}</td>
              <td>{{task.due_date_string}}</td>
              <td>{{task.is_complete}}</td>
            </tr>
          {% endfor %}
          </tbody>
      </table>
  </div>

  <br />
  <b>Add a Task:</b>
  <table>
  <tr>
    <td>Task</td>
    <td>
      <input id="task" type="text" name="action" size="50">
      <a id="cancel_edit" class="hint" href="javascript:cancelEdit()"></a>
    </td>
  </tr>
  <tr>
    <td>Due Date?</td>
    <td>
      <input id="due_date_yes" type="radio" name="has_due_date" value="yes">Yes
      <input id="due_date_no" type="radio" name="has_due_date" value="no" checked>No
    </td>
  </tr>
  <tr>
    <td valign="top">
      <input id="submit_button" type="submit" value="Add" onclick="addTask()">
    </td>
    <td><div id="due_date_cal" class="grid"></div></td>
  </tr>
  <tr>
    <td colspan="2"><div class="error" id="errorContainer"></div></td>
  </tr>
  </table>
  <input id="due_date" type="hidden" name="due_date" value="">

  <br />
  <a name="more" />
  <b>More:</b>
  <ul>
  <li>
    <a href="javascript:deleteAll()">Delete</a> all of this project's tasks
    <span id="delete_all_result" class="hint"></span>
  </li>
  </ul>

  {{footer}}

  <!-- YUI COMMON -->
  <!-- Dependencies -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
  <!-- END YUI COMMON -->

  <!-- YUI CALENDAR -->
  <!-- Source file -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/calendar/calendar-min.js"></script>
  <script>
    var selectedDueDate;

    YAHOO.namespace("example.calendar");

    function dateToLocaleString(dt, cal) {
      var wStr = cal.cfg.getProperty("WEEKDAYS_LONG")[dt.getDay()];
      var dStr = dt.getDate();
      var mStr = cal.cfg.getProperty("MONTHS_LONG")[dt.getMonth()];
      var yStr = dt.getFullYear();
      return (wStr + ", " + dStr + " " + mStr + " " + yStr);
    };

    function mySelectHandler(type,args,obj) {
      var selected = args[0];
      var selDate = this.toDate(selected[0]);

      selectedDueDate = dateToLocaleString(selDate, this);
      document.create_form.due_date.value = selectedDueDate;
    };

    YAHOO.example.calendar.cal1 = new YAHOO.widget.Calendar("cal1","due_date_cal", { title:"Choose a due date:", close:false });
    YAHOO.example.calendar.cal1.selectEvent.subscribe(mySelectHandler, YAHOO.example.calendar.cal1, true);
    YAHOO.example.calendar.cal1.render();

    // Listener to show the Calendar when "Yes" is clicked
    YAHOO.util.Event.addListener("due_date_yes", "click", YAHOO.example.calendar.cal1.show, YAHOO.example.calendar.cal1, true);

    // Listener to hide the Calendar when "No" is clicked
    YAHOO.util.Event.addListener("due_date_no", "click", YAHOO.example.calendar.cal1.hide, YAHOO.example.calendar.cal1, true);

    function updateCal(month, day, year) {
      if (!isNaN(month) && !isNaN(day) && !isNaN(year)) {
        var date = month + "/" + day + "/" + year;

        YAHOO.example.calendar.cal1.select(date);
        YAHOO.example.calendar.cal1.cfg.setProperty("pagedate", month + "/" + year);
        YAHOO.example.calendar.cal1.render();
      }
    }
  </script>
  <!-- END YUI CALENDAR -->

  <!-- YUI MENU -->
  <!-- Dependencies -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/container/container_core-min.js"></script>

  <!-- Source File -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/menu/menu-min.js"></script>
  <!-- END YUI MENU -->

  <!-- YUI DATATABLE -->
  <!-- Dependencies -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/element/element-beta-min.js"></script>
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/datasource/datasource-beta-min.js"></script>

  <!-- Source files -->
  <script type="text/javascript" src="http://yui.yahooapis.com/2.5.2/build/datatable/datatable-beta-min.js"></script>
  <script>
  var taskTable;
  var currentSortKey = "due";
  var currentSortDir = YAHOO.widget.DataTable.CLASS_ASC;

  formatDueDate = function(elCell, oRecord, oColumn, oData) {
    if (oData == "Invalid Date" || oData == "NaN") {
      elCell.innerHTML = "";
    }
    else {
      YAHOO.widget.DataTable.formatDate(elCell, oRecord, oColumn, oData);
    }
  };
  
  formatTask = function(cell, record, column, data) {
    data = getTaskAction(data);
    var complete = record.getData("is_complete");
    if (trueString(complete)) {
      cell.innerHTML = "<del>" + data + "</del>";
    }
    else {
      cell.innerHTML = data;
    }
  };

  YAHOO.util.Event.addListener(window, "load", function() {
      YAHOO.example.EnhanceFromMarkup = new function() {
          var myColumnDefs = [
              {key:"task", label:"Task", sortable:true, formatter:formatTask},
              {key:"due", label:"Due Date", sortable:true, formatter:formatDueDate},
              {key:"is_complete", label:"Complete?", sortable:true, hidden:false}
          ];

          this.myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("tasks"));
          this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
          this.myDataSource.responseSchema = {
              fields: [
                      {key:"task"},
                      {key:"due", parser:YAHOO.util.DataSource.parseDate},
                      {key:"is_complete"}
              ]
          };

          this.myDataTable = new YAHOO.widget.DataTable("project_section", myColumnDefs, this.myDataSource,
                  { sortedBy:{key:"due",dir:"asc"} }
          );
          taskTable = this.myDataTable;

          this.onContextMenuClick = function(p_sType, p_aArgs, p_myDataTable) {
              var task = p_aArgs[1];
              if(task) {
                  // Extract which TR element triggered the context menu
                  var elRow = this.contextEventTarget;
                  elRow = p_myDataTable.getTrEl(elRow);
                  var oRecord = p_myDataTable.getRecord(elRow);
                  var key = getTaskKey(oRecord.getData("task"));

                  if(elRow) {
                      switch(task.index) {
                          case 0:
                              editTask(key, elRow.id);
                              break;
                          case 1:
                              server.DeleteTask(
                                key, 
                                elRow.id, 
                                function(response) {taskTable.deleteRow(response);});
                              break;
                          case 2:
                              server.MarkTaskComplete(
                                key, 
                                elRow.id, 
                                function(response) {
                                  var data = oRecord.getData();
                                  data["is_complete"] = "True";
                                  taskTable.updateRow(response, data);
                                });
                              break;
                          case 3:
                              server.MarkTaskNotComplete(
                                key, 
                                elRow.id, 
                                function(response) {
                                  var data = oRecord.getData();
                                  data["is_complete"] = "False";
                                  taskTable.updateRow(response, data);
                                });
                              break;
                          case 4:
                              alert('Converting to a Next Action is not yet available...');
                              break;
                      }
                  }
              }
          };
          this.myContextMenu = new YAHOO.widget.ContextMenu("mycontextmenu", {trigger:this.myDataTable.getTbodyEl()});
          this.myContextMenu.addItem("Edit");
          this.myContextMenu.addItem("Delete");
          this.myContextMenu.addItem("Mark completed");
          this.myContextMenu.addItem("Mark not completed");
          this.myContextMenu.addItem("Convert to a Next Action");
          this.myContextMenu.render("project_section");
          this.myContextMenu.clickEvent.subscribe(this.onContextMenuClick, this.myDataTable);

          this.myDataTable.subscribe("columnSortEvent", function(oArgs) {
              currentSortKey = oArgs.column.key;
              currentSortDir = oArgs.dir;
          });
      };
  });
  </script>
  <!-- END YUI DATATABLE -->

  <!-- OTHER STUFF -->
  <!-- Dependencies -->
  <script type="text/javascript" src="./static/javascript/json2.js"></script>
  <script type="text/javascript" src="/static/javascript/gtd_utils.js"></script>
  <script type="text/javascript" src="/static/javascript/gtd_rpc.js"></script>
  <script>
  var deleteAllMsgTimeout;
  
  function editTask(key, rowId) {
    alert('Editing project tasks is not yet available...');
  }
  
  function deleteAll() {
    clearTimeout(deleteAllMsgTimeout);
    server.DeleteProjectTasks('{{project.key}}', onDeleteAllSuccess);
  }
  
  function onDeleteAllSuccess(response) {
    if (isError(response)) {
      $('delete_all_result').innerHTML = errorString(response);
    }
    else {
      $('delete_all_result').innerHTML = response;
      var length = taskTable.getRecordSet().getLength();
      if (length > 0) {
          taskTable.deleteRows(0, length);
      }
    }
    deleteAllMsgTimeout = setTimeout('$("delete_all_result").innerHTML = ""', 5000);
  }
  
  function addTask() {
    server.AddEditProjectTask(
      '{{project.key}}',
      $('task').value, 
      $('due_date_yes').checked, 
      selectedDueDate,
      false,
      null,
      onAddTaskSuccess);
  }

  function clearForm() {
    $('task').value = '';
    $('due_date_yes').checked = false;
    $('due_date_no').checked = true;
    YAHOO.example.calendar.cal1.hide();
  }
  
  function onAddTaskSuccess(response) {
    var record = YAHOO.widget.DataTable._cloneObject(response);
    taskTable.addRow(record);
    var column = taskTable.getColumn(currentSortKey);
    taskTable.sortColumn(column, currentSortDir);
    clearForm();
  }
  
  function editDescription() {
    $('edit_description').innerHTML = '';
    $('description').innerHTML = 
      '<input id="new_description" type="text" value="' + 
      $('description').innerHTML + 
      '"/><input type="submit" value="Go" onclick="doEditDescription()" />';
  }
  
  function doEditDescription() {
    server.EditProjectDescription('{{project.key}}', $('new_description').value, onEditDescriptionSuccess);
  }
  
  function onEditDescriptionSuccess(response) {
    $('description').innerHTML = response;
    $('edit_description').innerHTML = '(<a href="javascript:editDescription()">edit description</a>)';
  }
  </script>
  </body>
</html>
